//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/util/view_util.dart';

/// 线段绘画
class LinePainter extends CustomPainter {
  /// 线条颜色
  final Color color;

  /// 线条长度
  final double length;

  /// 是否是竖线，true为是
  final bool isVertical;

  /// 是否是虚线，true为是
  final bool isDashed;

  /// 线条宽度
  final double? lineWidth;

  LinePainter({
    super.repaint,
    required this.color,
    required this.length,
    this.isVertical = false,
    this.isDashed = false,
    this.lineWidth,
  });

  @override
  void paint(Canvas canvas, Size size) {
    /// 画笔
    Paint paint = Paint()
      ..color = color
      ..strokeWidth = lineWidth ?? 2
      ..style = PaintingStyle.stroke;

    /// 实现路径
    Path path = Path()..moveTo(0, 0);

    if (isVertical) {
      path.lineTo(0, length);
    } else {
      path.lineTo(length, 0);
    }

    Path linePath = path;
    if (isDashed) {
      /// 虚线路径
      linePath = _convertDashedPath(path);
    }

    /// 画线
    canvas.drawPath(linePath, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }

  /// 将实现路径专为虚线路径
  Path _convertDashedPath(Path path) {
    Path dashedPath = Path();

    /// 每根虚线的长度
    double dashedLength = 4;

    /// 每根虚线的间隔
    double dashedGap = 2;

    // 虚线Path转换的核心，需要理解下面两个代码：
    // 1、path.computeMetrics()，获取Path的轮廓。
    // 2、metric.extractPath(distance, distance +dottedLength)，从轮廓中获取裁剪出子Path。

    for (var metric in path.computeMetrics()) {
      double distance = 0;
      bool isDrawDotted = true;
      while (distance < metric.length) {
        if (isDrawDotted) {
          dashedPath.addPath(
              metric.extractPath(distance, distance + dashedLength),
              Offset.zero);
          distance += dashedLength;
        } else {
          distance += dashedGap;
        }
        isDrawDotted = !isDrawDotted;
      }
    }

    return dashedPath;
  }
}
